/**
 * 递归查找，获取 children
 */
const getChildren = (data, result, pid) => {
  for (const item of data) {
    if (item.pid === pid) {
      const newItem = {...item, children: []}
      result.push(newItem)
      getChildren(data, newItem.children, item.id)
    }
  }
}

/**
 * 转换方法
 */
const arrayToTree = (data, pid) => {
  const result = []
  getChildren(data, result, pid)
  return result
}

// 测试
let arr = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 1},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门4', pid: 3},
  {id: 5, name: '部门5', pid: 4}
]
const res = arrayToTree(arr, 0)
console.log(res)


formatDataTree(data)

// 递归
function formatDataTree(data) {
  let parents = data.filter(p => p.pid === 0)
  let children = data.filter(c => c.pid !== 0)

  dataToTree(parents, children)
  return parents

  function dataToTree(parents, children) {
    parents.map(p => {
      children.map((c, i) => {
        if (p.id === c.pid) {
          let _children = JSON.parse(JSON.stringify(children))
          _children.splice(i, 1)
          dataToTree([c], _children)
          if (p.children) {
            p.children.push(c)
          } else {
            p.children = [c]
          }
        }
      })
    })
  }
}

// 非递归
function formatDataTree(data) {
  let _data = JSON.parse(JSON.stringify(data))
  return _data.filter(p => {
    const _arr = _data.filter(c => c.pid === p.id)
    _arr.length && (p.children = _arr)
    return p.pid === 0
  })
}